import { useMutation } from '@tanstack/vue-query'
import { ref, type Ref } from 'vue'
import { useRoute } from 'vue-router'

import { ApiExecuteMimoPlot, ModulationMode, labMessage, type MimoPlotArgs } from '@/apis/lab'
import { queryClient } from '@/apis/client'
import { useFetchMessage } from '@/composables/useFetchMessage'
import { LabID } from '@/constants/lab'
import { useGetReportQueryKey } from '@/apis/report'

export function useMimoPlotForm(reportID: Ref<number>) {
  const formState = ref<MimoPlotArgs>({
    receiveAntennas: 1,
    modulationMode: ModulationMode.FourASK,
    noiseRate: 0,
    counts: 1000
  })

  const { showMessage } = useFetchMessage([labMessage])

  const { mutate } = useMutation({
    mutationFn: ApiExecuteMimoPlot,
    onSettled(data, error) {
      showMessage(data?.code ?? error?.data?.code)
    },
    onSuccess() {
      queryClient.invalidateQueries({ queryKey: useGetReportQueryKey(reportID) })
    }
  })

  const route = useRoute()
  const handleSubmit = () => {
    mutate({
      classID: +route.params.classID,
      experimentID: LabID.MIMOSimulator,
      args: formState.value
    })
  }

  return {
    formState,
    handleSubmit
  }
}
